package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.HashMap;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {
    @Value("${tencent.map.key}")
    private String mapKey;
    @Resource
    private RestTemplate restTemplate;

    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        // 1. 根据传过来的起始位置的经纬度，计算路线信息 。 下面是调用腾讯地图api的格式
        // https://apis.map.qq.com/ws/direction/v1/driving/?from=39.915285,116.403857&to=39.915285,116.803857&output=json&key=[你的key]
        // 2. 将起始位置 经纬度，存入hashmap中
        HashMap<String, String> locationMap = new HashMap<>();
        locationMap.put("from", calculateDrivingLineForm.getStartPointLatitude() + ","
                + calculateDrivingLineForm.getStartPointLongitude());
        locationMap.put("to", calculateDrivingLineForm.getEndPointLatitude() + ","
                + calculateDrivingLineForm.getEndPointLongitude());
        locationMap.put("key", mapKey);

        // 2. 远程调用腾讯地图服务
        JSONObject response = restTemplate.getForObject(url, JSONObject.class, locationMap);
        // 3. 判断是否返回正确
        if (response.getIntValue("status") != 0) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // 4. 获取路线结果信息，因为可能有多条路线，我们只取第一条
        JSONObject route = response.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        // 总距离 单位米
        BigDecimal distance = route.getBigDecimal("distance").divide(new BigDecimal("1000")).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 总耗时
        BigDecimal duration = route.getBigDecimal("duration");
        // 方案路线坐标点串
        JSONArray polyline = route.getJSONArray("polyline");
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        drivingLineVo.setDistance(distance);
        drivingLineVo.setPolyline(polyline);
        drivingLineVo.setDuration(duration);
        return drivingLineVo;
    }
}
